package com.itheima.sh.controller;

import com.github.pagehelper.Page;
import com.itheima.sh.pojo.User;
import com.itheima.sh.response.Result;
import com.itheima.sh.response.StatusCode;
import com.itheima.sh.service.UserService;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Restful 风格
 * @Description:
 * @Version: V1.0
 */
//@Controller  // 必须是Controller
//@ResponseBody   // response从写 write
@RestController
// （对象类型 --> JSON，并且设置contentType:application/josn）
// String：直接通过write方法响应给浏览器，并且设置contentType:text/html
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping
    public Result findAll(){

//        try {
//            return Result.okResult(userService.findAll());
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.errorResult(StatusCode.ERROR);
//        }
        return Result.okResult(userService.findAll());
    }

    // @RequestParam : key=value&key=value
    // @RequestBody : {}  []
    @PostMapping  // POST 请求
    public Result add( @RequestBody User user) {



        boolean b = userService.add(user);
        return Result.okResult(user);
    }

    /**
     * 删除用户
     * @param uuid
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer uuid) {
        boolean b = userService.delete(uuid);
        return new Result(b ? 200 : 400, b ? "删除成功" : "删除失败");
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping
    public Result<User> update(@RequestBody User user) {
        boolean b = userService.update(user);
        return new Result<User>(b ? 200 : 400, b ? "修改成功" : "修改失败");
    }

    /**
     * 带条件分页查询
     * @param page 当前页，从1开始
     * @param size 一页显示记录数
     * @return
     */
    @GetMapping("/search/{page}/{size}")
    public Result<User> search(@RequestBody User user, 	@PathVariable("page") Integer page,
                               @PathVariable("size") Integer size){
        Page<User> pages = userService.search(user,page, size);
        // 数据列表，总记录，总页数
//        PageResult pageResult =
//                new PageResult<>(pages.getTotal(),pages.getPages(),pages.getResult());

        return new Result(200, "查询成功", pages);
    }
}